//
//  DMInAppPurchaseHandleManager.m
//  DMPolymerizeSDK
//
//  Created by little People on 2023/6/16.
//

#import "DMInAppPurchaseHandleManager.h"

@implementation DMInAppPurchaseHandleManager

static DMInAppPurchaseHandleManager *_InAppPurchaseHandleManager = nil;
+ (instancetype)shareInAppPurchaseHandleManager {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _InAppPurchaseHandleManager = [[self alloc] init];
    });
    return _InAppPurchaseHandleManager;
}

- (NSDictionary *)skproductInfo:(NSString *)productId {
    if (productId.length == 0) {
        return nil;
    }
    
    NSArray<SKProduct *> *products = [DMInAppPurchaseHandleManager shareInAppPurchaseHandleManager].productIds;
    if (![products isKindOfClass:[NSArray class]] || products.count == 0) {
        return nil;
    }
    
    for (SKProduct *product in products) {
        if (![product isKindOfClass:[SKProduct class]]) {
            continue;
        }
        
        NSString *pid = product.productIdentifier;
        if ([pid isEqualToString:productId]) {
            NSString *currency = product.priceLocale.currencyCode ?: @"";
            
            // 保证价格是字符串且安全
            NSString *priceString = product.price ? product.price.stringValue : @"";
            
            NSString *title = product.localizedTitle ?: @"";
            
            return @{
                @"currency": currency,
                @"price": priceString,
                @"title": title
            };
        }
    }
    
    return nil;
}

@end
